package com.favorite;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution207 {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] rudu = new int[numCourses];
        LinkedList<Integer> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            list.add(new ArrayList<>());
        }
        for (int[] prerequisite : prerequisites) {
            rudu[prerequisite[0]]++;
            list.get(prerequisite[1]).add(prerequisite[0]);
        }
        for (int i = 0; i < numCourses; i++) {
            if (rudu[i] == 0) queue.add(i);
        }
        while (!queue.isEmpty()) {
            int cur = queue.removeFirst();
            numCourses--;
            List<Integer> integerList = list.get(cur);
            for (Integer integer : integerList) {
                rudu[integer]--;
                if (rudu[integer] == 0) queue.add(integer);
            }
        }
        return numCourses == 0;
    }
}
